﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Openlab.Tools.CodeGender.Funtions
{

    public class GetEntityFunc : Function
    {
        string entityClass;
        string getEntitiesFuncName;
        string entityCacheName;
        Column idColumn;

        string paramEntity, paramId;
        string paramEntities, paramIds;

        public GetEntityFunc(string entityClass, string getEntitiesFuncName
            , string entityCacheName, Column idColumn)
            : base(
                string.Format("Get{0}", entityClass)
                , string.Format("static {0}", entityClass)
                , null)
        {
            this.entityClass = entityClass;
            this.getEntitiesFuncName = getEntitiesFuncName;
            this.entityCacheName = entityCacheName;
            this.idColumn = idColumn;
            string idType = idColumn.CSTypeName;

            paramEntity = entityClass.ToFirstLower();
            paramId =idColumn.Name.ToFirstLower();
            paramEntities = entityClass.ToFirstLower().ToPlural();
            paramIds = idColumn.Name.ToFirstLower().ToPlural();

            Parameters = new List<FunctionParameter>();
            Parameters.Add(new FunctionParameter(paramId, string.Format("{0}", idType)));
            Parameters.Add(new FunctionParameter("cacheable", "bool"));
        }


        public override string Body
        {
            get
            {
                string template = @"
[EntityClass] [ParamEntity] = null;
if (!cacheable ||
    ![EntityCache].TryGetValue([ParamEntityId], out [ParamEntity]))
{
    [IdType][] [ParamEntityIds] = new [IdType][] { [ParamEntityId] };
    List<[EntityClass]> [ParamEntities] = [GetEntitiesFunc]([ParamEntityIds], cacheable);
    if ([ParamEntities] != null && [ParamEntities].Count == 1)
    {
        [ParamEntity] = [ParamEntities][0];
    }
}
return [ParamEntity];
";

                template = template.Replace("[ParamEntityIds]", paramIds);
                template = template.Replace("[ParamEntities]", paramEntities);
                template = template.Replace("[ParamEntityId]", paramId);
                template = template.Replace("[ParamEntity]", paramEntity);
                template = template.Replace("[IdType]", idColumn.CSTypeName);
                template = template.Replace("[EntityClass]", entityClass);
                template = template.Replace("[EntityCache]", entityCacheName);
                template = template.Replace("[GetEntitiesFunc]", getEntitiesFuncName);

                return template;
            }
        }
    }

}
